<template>
  <div class="container MaterialPackageBox" style="width:99%;margin-top:-25px;">
    <div class="materielName">{{materielName}}</div>
    <!-- 查询条件 -->
    <div class="query-box">
      <el-form :model="displayPageParams" status-icon ref="queryBox">
        <el-row>
          <el-col :span="4" v-if='displayPageParams.manageType==1||displayPageParams.manageType==3'>
            <div class="depart-box">
              <div class="slect-title">{{displayPageParams.manageType==1?'物料类别':'素材类别'}}</div>
              <el-select
                clearable
                filterable
                v-model="displayPageParams.materielType"
                filterable
                :disabled="true"
              >
                <el-option
                  v-for="item in materiel_type_option"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                  
                ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <el-form-item label prop="customerNumber">
                <el-input
                  v-model="displayPageParams.code"
                  :disabled="true"
                >
                  <template slot="prepend">{{displayPageParams.manageType==1?'物料编码':(displayPageParams.manageType=='2'?'活动编码':'素材编码')}}</template>
                </el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">分类</div>
              <el-select clearable v-model="displayPageParams.platformType" :disabled="true" filterable>
                <el-option
                  v-for="item in bc_material_platform_type_options"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div class="from-btns">
        <!-- <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button
          :label="$t('action.search')"
          perms="true"
          type="primary"
          @click="search"
        /> -->
      </div>
    </div>
    <!-- 批量删除按钮 -->
    <div class="add-btns fl">
      <kt-button
        :label="$t('批量上传')"
        perms="MaterialMange:MaterialPackage:upload"
        type="primary"
        @click="addAllSelection"
      />
    </div>
    <div class="fr">
      <kt-button
        :label="$t('新增')"
        type="primary"
        perms="MaterialMange:MaterialPackage:add"
        @click="handleNewADD"
      ></kt-button>
    </div>
    <!--表格内容栏-->
    <div class="btn">
      <Crm-table
        class="table-width"
        MaterialPackage
        width="400"
        :showBatchDelete="false"
        :dominIMGUrl='dominIMGUrl'
        permsEdit="MarketingManage:MaterialPackage:edit"
        permsDelete="MarketingManage:MaterialPackage:delete"
        permsDownLoad="MarketingManage:MaterialPackage:downLoad"
        :data="pageResult"
        :columns="columns"
        :loading="loading"
        @findPage="findPage"
        @handleDownLoad="handleDownLoad"
        @handleDeleteDic="handleDeleteDic"
        @handleEdit="handleEdit"
        @changeSwitch="changeSwitch"
        @handleTop="handleTop"
        @handleDown="handleDown"
        :baseUrl="baseUrl"
      ></Crm-table>
    </div>
    <!-- 编辑弹窗 -->
    <Material-Package-EidtPop
      :dialogVisibleEdit="dialogVisibleEdit"
      :dataFormAdd="dataFormAdd"
      @submitAdd="submitAdd"
      @closeMPEPop="closeMPEPop"
      :displayPageParams='displayPageParams'
      :baseUrl="baseUrl"
      @mediaTypeChange="mediaTypeChange"
    >
    </Material-Package-EidtPop>
    <!-- 新增 -->
    <el-dialog
      title="新增"
      :visible.sync="newAddVisible"
      @close="closeNewPop"
      width="50%"
    >
      <el-form label-width="110px" :model="newDataFormAdd" ref="newDataFormAdd">
        <el-form-item label="文件名称">
          <el-input
            v-model="newDataFormAdd.mediaName"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件大小">
          <el-input
            type="number"
            v-model="newDataFormAdd.mediaSize"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件格式">
          <el-input
            v-model="newDataFormAdd.mediaStyle"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="closeNewPop">{{
          $t("action.cancel")
        }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitNewAdd('newDataFormAdd')"
          :loading="editLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <!-- 上传弹出框 -->
    <el-dialog
      :title="formTitle"
      :visible.sync="editVisible"
      :close-on-click-modal="false"
      @close="closeUpload"
      width="800px"
    >
      <WebUpload
        :fileNumLimit="fileNumLimit"
        :fileSize="fileSize"
        :chunkSize="chunkSize"
        :uploadSuffixUrl="uploadSuffixUrl"
        :options="options"
        :fileListData="fileList"
        :materielId="materielId"
        ref="anyName"
      >
      </WebUpload>
      <span slot="footer" class="dialog-footer">
        <!--<el-button @click="editVisible = false">取 消</el-button>-->
        <!-- <el-button type="primary" @click="saveEdit">确 定</el-button> -->
      </span>
    </el-dialog>

    <!--图片查看-->
    <el-dialog title="图片查看" :visible.sync="showImgVisible" width="800px">
      <el-image
        v-if="imageUrl"
        class="avatar"
        :src="imageUrl"
        :preview-src-list="[imageUrl]"
      ></el-image>
      <span slot="footer" class="dialog-footer">
        <!--<el-button @click="editVisible = false">取 消</el-button>-->
        <el-button
          type="primary"
          @click="
            showImgVisible = false;
            imageUrl = '';
          "
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { regionDataPlus } from "element-china-area-data";
import { CodeToText } from "element-china-area-data";
import WebUpload from "@/components/common/upload/WebUpload";
import MaterialPackageEidtPop from "@/components/Popup/MaterialPackageEidtPop";
import axios from "axios";
import Cookies from "js-cookie";
import { baseUrl } from "@/utils/global";
export default {
  name: "Chinaedu",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch,
    WebUpload,
    MaterialPackageEidtPop
  },
  data() {
    return {
      // 查询条件
      isopen: [
        {
          value: "解锁",
          label: "1"
        },
        {
          value: "锁定",
          label: "2"
        }
      ],
      queryBox: {
        materielId: this.$route.query.id,
      },
      displayPageParams:{
        materielType:this.$route.query.materielType,//物料类型
        platformType:this.$route.query.platformType,//平台类型（分类）
        code:this.$route.query.code,
        manageType:this.$route.query.manageType //物料包类型
      },
      student_data_from_type_options: [],
      student_progress_change: [],
      student_progress_options: [],
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "name", label: "文件名称", minWidth: 120 },
        { prop: "mediaSizeStr", label: "文件大小", minWidth: 100 },
        { prop: "style", label: "文件格式", minWidth: 190 },
        { prop: "updateTime", label: "更新时间", minWidth: 100 }
      ],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {
        content: []
      },
      materiel_type_option: [],
      loading: false, // 加载标识
      formTitle: "添加",
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      uId: 0,
      id: -1,
      loading: true,
      uploadLoading: false,
      showRemoveFile: false,

      imageUrl: "",
      showImgVisible: false,
      uploader: {},
      uploadBtnDisabled: false,
      uploadStaus: "el-icon-upload",
      fileList: [], //显示集合
      chunked: true, //是否开启分片上传
      fileNumLimit: 200, //文件总数
      fileSize: 100 * 1024 * 1024 * 1024, //默认上传文件大小
      chunkSize: 30 * 1024 * 1024, //默认文件片段
      uploadSuffixUrl: baseUrl,
      options: {
        compress:null,
        //允许上传的文件
        fileType:
          "",
        fileUploadUrl: "/mediaInfo/chunkUpload", //上传地址
        fileCheckUrl: "/mediaInfo/checkFile", //检测文件是否存在url
        checkChunkUrl: "/mediaInfo/checkFile", //检测分片url
        // mergeChunksUrl: "/upload/fileRecord/zone/upload/merge/", //合并文件请求地址
        headers: {}
      },
      materielId: this.$route.query.id,
      dialogVisibleEdit: false,
      baseUrl: baseUrl,
      dataFormAdd: {
        id: ""
      },
      editLoading: false,
      size: "samll",
      imgUrl: "",
      newAddVisible: false,
      newDataFormAdd:{},
      materielName:this.$route.query.materielName,//物料包名称
      bc_material_platform_type_options:[],
      pageManageType:this.$route.query.manageType,
      dominIMGUrl:JSON.parse(localStorage.getItem('dominIMGUrl'))
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading = true;

      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },
    get_downList() {
      if(this.displayPageParams.manageType==3){
        this.materiel_type_option = JSON.parse(
          localStorage.getItem("bcMaterialType")
        );
      }else{
        this.materiel_type_option = JSON.parse(
          localStorage.getItem("materielTypeOption")
        );
      }
      // this.$api.user.optionsList({ codeType: "bc_materiel_type" }).then(res => {
      //   this.materiel_type_option = res.keyValueList;
      // });
      // 分类
      this.bc_material_platform_type_options = JSON.parse(
        localStorage.getItem("bcMaterialPlatformType")
      );
    },
    handleChange(value) {
      // console.log(value);
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.$api.agent.mediaInfoList(this.queryBox).then(res => {
        if (res.result == 1) {
          this.loading = false;
          let content = { content: res.data, totalSize: res.total };
          this.pageResult = content;
          this.pageResult.content.forEach(item => {
            // this.materiel_type_option.forEach(mtItem=>{
            //   if(mtItem.key==item.materielType){
            //     item.materielTypeStr=mtItem.value
            //   }
            // })
            // this.bc_material_platform_type_options.forEach(pItem=>{
            //   if(pItem.key==item.platformType){
            //     item.platformTypeStr=pItem.value
            //   }
            // })
            // this.bc_materiel_use_state_options.forEach(bcusItem=>{
            //   if(bcusItem.key==item.onlineState){
            //     item.onlineStateStr=bcusItem.value
            //   }
            // })
            item.mediaSizeStr = this.formatFileSize(item.mediaSize);
          });
          // let hash = {}; 
          // const data2 = this.pageResult.content.reduce((preVal, curVal) => {
          //     hash[curVal.mediaInfoId] ? '' : hash[curVal.mediaInfoId] = true && preVal.push(curVal); 
          //     return preVal 
          // }, [])
          // this.pageResult.content=data2
        }else{
          this.$message.error(res.msg);
        }
      });
    },
    formatFileSize(size) {
      var fileSize = 0;
      if (size / 1024 > 1024) {
        var len = size / 1024 / 1024;
        fileSize = len.toFixed(2) + "MB";
      } else if (size / 1024 / 1024 > 1024) {
        var len = size / 1024 / 1024;
        fileSize = len.toFixed(2) + "GB";
      } else {
        var len = size / 1024;
        fileSize = len.toFixed(2) + "KB";
      }
      return fileSize;
    },
    // 重置
    reset(queryBox) {
      this.$refs.queryBox.resetFields();
      this.queryBox.materielType = "";
      this.queryBox.code = "";
      this.queryBox.name = "";
      this.queryBox.platformType = "";
      this.queryBox.userId = "";
      this.findPage(null);
    },
    addAllSelection() {
      //添加数据
      this.form = {
        isFilter: "1",
        contentType: "",
        fileSuffix: "",
        fileType: "",
        fileTag: "",
        fileDescribe: ""
      };
      this.formTitle = "上传文件";
      this.editVisible = true;
    },
    closeUpload() {
      this.$refs.anyName.clearFiles();
      this.fileList = [];
      this.findPage(null)
    },
    handleEdit(params) {
      this.dataFormAdd = params.row;
      this.dataFormAdd.id = params.row.mediaTypeId;
      this.imgUrl = params.row.previewUrl;
      this.dialogVisibleEdit = true;
    },
    changeSwitch(params) {
      this.$api.agent
        .mediaTypeInfoUpdate({
          id: params.row.mediaTypeId,
          state: params.row.state
        })
        .then(res => {
          if (res.result == 1) {
            this.$message.success(res.msg);
            this.findPage(null);
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    // 下载
    handleDownLoad(params) {
      // let ids = params.row.mediaInfoId;
      // this.$api.agent.mediaTypeInfoDownload({id:ids}).then(res => {
      //   if (res.result == 1) {
      //     this.$message.success(res.msg);
      //     this.findPage(null);
      //   } else {
      //     this.$message.error(res.msg);
      //   }
      // });
    },
    // 删除
    handleDeleteDic(params) {
      this.$confirm("确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$api.agent.mediaTypeInfodelete({ id: params.row.mediaTypeId }).then(res => {
          if (res.result == 1) {
            this.$message.success(res.msg);
            this.findPage(null);
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 编辑提交
    submitAdd(params) {
      this.$api.agent.mediaTypeInfoUpdate(params).then(res => {
        if (res.result == 1) {
          this.$message.success(res.msg);
          this.findPage(null);
          this.dialogVisibleEdit = false;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    closeMPEPop(params) {
      this.dialogVisibleEdit = false;
      this.dataFormAdd={
        id:'',
        mediaType:''
      }
    },
    // 文件类型改变
    mediaTypeChange(value) {
      if (value == 1) {
        this.useInfo = true;
      }
    },
    handleNewADD() {
      this.newAddVisible = true;
    },
    closeNewPop(){
      this.newAddVisible = false;
    },
    submitNewAdd(){
      this.newDataFormAdd.state=1
      this.newDataFormAdd.materielId=this.$route.query.id
      this.$api.agent.mediaTypeInfoCreate(this.newDataFormAdd).then(res=>{
        if(res.result==1){
          this.$message.success(res.msg)
          this.newAddVisible=false
          this.findPage(null)
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    handleTop(params){
      this.pageResult.content.forEach((item,index)=>{
        if(item.mediaTypeId==params.row.mediaTypeId){
          this.$api.agent.mediaTypeInfoChangePlace({id1:params.row.mediaTypeId,id2:this.pageResult.content[index-1].mediaTypeId}).then(res=>{
            if (res.result == 1) {
              this.$message.success(res.msg);
              this.findPage(null);
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
      
    },
    handleDown(params){
      this.pageResult.content.forEach((item,index)=>{
        if(item.mediaTypeId==params.row.mediaTypeId){
          this.$api.agent.mediaTypeInfoChangePlace({id1:params.row.mediaTypeId,id2:this.pageResult.content[index+1].mediaTypeId}).then(res=>{
            if (res.result == 1) {
              this.$message.success(res.msg);
              this.findPage(null);
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    }
  },
  mounted() {
    this.get_downList();
  }
};
</script>
<style>
@import url("../../assets/queryBox.css");
</style>
<style lang="scss" scoped>
.checked-person {
  font-weight: 500;
  display: inline-block;
  text-align: center;
  margin: 3% 0 3% 0;
}
.batchdistribution-pop-tit {
  font-size: 20px;
  font-weight: bold;
  display: inline-block;
  color: #303133;
}
.demo-form-inline {
  width: 90%;
  margin: 0 auto;
  .el-dialog__body .el-input {
    width: 93% !important;
  }
  .el-select {
    width: 100% !important;
  }
  .tit {
    display: inline-block;
    margin-top: 10%;
  }
}
.el-row .el-col {
  margin-left: 0;
}
.query-box .el-row .el-col {
  margin-left: 2%;
}
.el-dialog__wrapper .el-form-item__content {
  margin-left: 0;
}
</style>
<style lang="scss">
.batchdistribution-pop .el-dialog__header {
  padding: 0 0 0 0 !important;
}
.MaterialPackageBox{
  .el-form-item{
    width: 100%;
  }
  .materielName{
    font-weight: bold;
    text-align: left;
    padding: 10px;
    margin-left: 2%;
    font-size: 30px;
  }
}

</style>
